import os
from django.shortcuts import render
import json
from random import randrange
import jieba  # 导入第三方分词库
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from django.http import HttpResponse
import pandas as pd
import numpy as np
from pandas import read_csv
from rest_framework.views import APIView
from pyecharts.charts import Bar
from pyecharts import options as opts
from blog.models import Catagory
import base64
from io import BytesIO
from wordcloud import WordCloud
import matplotlib

matplotlib.use('TkAgg')


def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    data.update(kwargs)
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error


def bar_base():
    bar_title = "bar_title"
    bar_subtitle = "bar_title"
    x = []
    x_title = "bar_title"
    y_values = []
    print(bar_title, bar_subtitle, x, x_title, y_values)
    c = (
        Bar()
            .add_xaxis(x)
            # .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)])
            # .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)])
            .add_yaxis(x_title, y_values)
            .set_global_opts(title_opts=opts.TitleOpts(title=bar_title, subtitle=bar_subtitle),
                             toolbox_opts=opts.ToolboxOpts(orient='vertical', pos_left='right', pos_top='middle'),
                             legend_opts=opts.LegendOpts(is_show=False),
                             datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_='inside')],
                             )
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                    opts.MarkPointItem(type_="average", name="平均值"),
                ]
            ),
        )
            .dump_options_with_quotes()
    )
    return c


class ChartView(APIView):
    def get(self, *args, **kwargs):
        return JsonResponse(json.loads(bar_base()))


class IndexView(APIView):
    def get(self, request, *args, **kwargs):
        # return HttpResponse(content=open("./templates/bar_chart.html", encoding='UTF-8').read())
        return render(request, 'bar_chart.html')


def get_barDate(request):
    # if request.method == "POST":
    # bar_title = request.POST.get('bar_title', None)
    # bar_subtitle = request.POST.get('bar_subtitle', None)
    # x_value = list(request.POST.get('x_values', None))
    # y_value = list(request.POST.get('y_values', None))
    # x_title = request.POST.get('x_title', None)
    # bar_base(bar_title, bar_subtitle, x_value, y_value, x_title)
    # print(bar_title, bar_subtitle, x_value, y_value, x_title)
    return render(request, 'bar_chart.html')


# 柱状图
def bar(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    local_filename = "media/upload/"
    filename = os.listdir(local_filename)
    filename.sort(key=lambda fn: os.path.getatime(local_filename + fn) if not os.path.isdir(local_filename + fn) else 0)
    df = pd.read_csv('media/upload/{}'.format(filename[-1]), encoding='utf8')
    if request.method == "POST" and request.POST:
        bar_title = request.POST.get('bar_title', None)
        x_value = request.POST.get('x_values', None)
        y_value = request.POST.get('y_values', None)
        x_title = request.POST.get('x_title', None)
        xx_values = x_value.split(",")
        yy_values = y_value.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        message = '创建成功'
        print(df.head())
        print(yy_values)
        print(type(bar_title), type(xx_values), type(yy_values), type(x_title))
    return render(request, 'bar_demo.html', locals())


# 保存文件
def save_barfile(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST":
        f = request.FILES['csv_file']
        print(type(f))
        file_path = os.path.join('media/upload', f.name)
        with open(file_path, 'wb') as fp:
            for info in f.chunks():
                fp.write(info)
            fp.close()
            message = '上传成功'
        data_set = read_csv(file_path, encoding='utf8')
        print(data_set.head())
        x_title = np.array(data_set.columns.values)  # 获取表头
        x_value = data_set['作物']
        y_value = data_set['数量']
        print(list(x_value))
        print(list(y_value))
        print(x_title)
        return render(request, 'bar_demo.html', locals())
    else:
        message = '上传失败'
    return render(request, 'bar_demo.html', locals())


# 箱型图
def box(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST" and request.POST:
        bar_title = request.POST.get('bar_title', None)
        sub_title = request.POST.get('sub_title', None)
        data_set = request.POST.get('data_set', None)
        yy_values = data_set.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        message = '图表创建成功'
        # print(bar_title,sub_title,yy_values)
        # print(type(yy_values))
    return render(request, 'box_chart.html', locals())


# 保存文件
def save_kfile(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST":
        f = request.FILES['csv_file']
        print(type(f))
        file_path = os.path.join('media/upload', f.name)
        with open(file_path, 'wb') as fp:
            for info in f.chunks():
                fp.write(info)
            fp.close()
            message = '上传成功'
        data_set = read_csv(file_path, encoding='utf8')
        print(data_set.head())
        return render(request, 'k_chart.html', locals())
    else:
        message = '上传失败'
    return render(request, 'k_chart.html', locals())


# K线图
def k_chart(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    local_filename = "media/upload/"
    filename = os.listdir(local_filename)
    filename.sort(key=lambda fn: os.path.getatime(local_filename + fn) if not os.path.isdir(local_filename + fn) else 0)
    df = pd.read_csv('media/upload/{}'.format(filename[-1]), encoding='utf8')
    if request.method == "POST" and request.POST:
        k_title = request.POST.get('k_title', None)
        sub_title = request.POST.get('sub_title', None)
        dataSet = df.values.tolist()
        print(dataSet)
        k_message = '创建成功'
        print(sub_title, k_title)
    return render(request, 'k_chart.html', locals())


# 折线图
def line(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST" and request.POST:
        line_title = request.POST.get('line_title', None)
        x_value = request.POST.get('x_values', None)
        y_value = request.POST.get('y_values', None)
        x_title = request.POST.get('x_title', None)
        xx_values = x_value.split(",")
        yy_values = y_value.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        print(line_title, x_title, xx_values, yy_values)
        message = '创建成功'
    return render(request, 'Line_chart.html', locals())


# 漏斗图
def funnel(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST" and request.POST:
        funnel_title = request.POST.get('funnel_title', None)
        funnel_legend = request.POST.get('funnel_legend', None)
        funnel_legend1 = funnel_legend.split(",")
        sub_title = request.POST.get('sub_title', None)
        dataset = request.POST.get('dataset', None)
        yy_values = dataset.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        newdata = dict(zip(funnel_legend1, yy_values))
        print(newdata)
        message = '创建成功'
        print(funnel_legend1, sub_title, yy_values)
    return render(request, 'funnel_chart.html', locals())


# 饼图
def pie(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST" and request.POST:
        pie_title = request.POST.get('pie_title', None)
        pie_legend = request.POST.get('pie_legend', None)
        pie_legend1 = pie_legend.split(",")
        sub_title = request.POST.get('sub_title', None)
        dataset = request.POST.get('dataset', None)
        yy_values = dataset.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        newdata = dict(zip(pie_legend1, yy_values))
        print(newdata)
        message = '创建成功'
        print(pie_legend1, sub_title, yy_values)
    return render(request, 'pie_chart.html', locals())


# 保存文件
def save_rfile(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST":
        f = request.FILES['csv_file']
        print(type(f))
        file_path = os.path.join('media/upload', f.name)
        with open(file_path, 'wb') as fp:
            for info in f.chunks():
                fp.write(info)
            fp.close()
            message = '上传成功'
        data_set = read_csv(file_path, encoding='utf8')
        print(data_set.head())
        return render(request, 'radar_chart.html', locals())
    else:
        message = '上传失败'
    return render(request, 'radar_chart.html', locals())


# 雷达图
def radar(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    local_filename = "media/upload/"
    filename = os.listdir(local_filename)
    filename.sort(key=lambda fn: os.path.getatime(local_filename + fn) if not os.path.isdir(local_filename + fn) else 0)
    df = pd.read_csv('media/upload/{}'.format(filename[-1]), encoding='utf8')
    if request.method == "POST" and request.POST:
        r_title = request.POST.get('r_title', None)
        sub_title = request.POST.get('sub_title', None)
        dataSet = df.values.tolist()
        print(dataSet)
        r_message = '创建成功'
        print(sub_title, r_title)
    return render(request, 'radar_chart.html', locals())


# 日历图
def calendar(request):
    # if request.method == "POST" and request.POST:
    #     bar_title = request.POST.get('bar_title', None)
    #     x_value = request.POST.get('x_values', None)
    #     y_value = request.POST.get('y_values', None)
    #     x_title = request.POST.get('x_title', None)
    #     xx_values = x_value.split(",")
    #     yy_values = y_value.split(",")
    #     yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
    #     print(type(bar_title), type(xx_values), type(yy_values), type(x_title))
    #     context = {
    #         'bar_title': bar_title,
    #         'x_value': xx_values,
    #         'y_value': yy_values,
    #         'x_title': x_title,
    #     }
    #     print(context)
    return render(request, 'calendar.html', locals())


# 3D柱状图
def threeD_bar(request):
    # if request.method == "POST" and request.POST:
    #     bar_title = request.POST.get('bar_title', None)
    #     x_value = request.POST.get('x_values', None)
    #     y_value = request.POST.get('y_values', None)
    #     x_title = request.POST.get('x_title', None)
    #     xx_values = x_value.split(",")
    #     yy_values = y_value.split(",")
    #     yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
    #     print(type(bar_title), type(xx_values), type(yy_values), type(x_title))
    #     context = {
    #         'bar_title': bar_title,
    #         'x_value': xx_values,
    #         'y_value': yy_values,
    #         'x_title': x_title,
    #     }
    #     print(context)
    return render(request, '3D_Bar.html', locals())


# 3D折线图
def threeD_Line(request):
    # if request.method == "POST" and request.POST:
    #     bar_title = request.POST.get('bar_title', None)
    #     x_value = request.POST.get('x_values', None)
    #     y_value = request.POST.get('y_values', None)
    #     x_title = request.POST.get('x_title', None)
    #     xx_values = x_value.split(",")
    #     yy_values = y_value.split(",")
    #     yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
    #     print(type(bar_title), type(xx_values), type(yy_values), type(x_title))
    #     context = {
    #         'bar_title': bar_title,
    #         'x_value': xx_values,
    #         'y_value': yy_values,
    #         'x_title': x_title,
    #     }
    #     print(context)
    return render(request, '3D_Line.html', locals())


# 3D散点图
def threeD_scatter(request):
    # if request.method == "POST" and request.POST:
    #     bar_title = request.POST.get('bar_title', None)
    #     x_value = request.POST.get('x_values', None)
    #     y_value = request.POST.get('y_values', None)
    #     x_title = request.POST.get('x_title', None)
    #     xx_values = x_value.split(",")
    #     yy_values = y_value.split(",")
    #     yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
    #     print(type(bar_title), type(xx_values), type(yy_values), type(x_title))
    #     context = {
    #         'bar_title': bar_title,
    #         'x_value': xx_values,
    #         'y_value': yy_values,
    #         'x_title': x_title,
    #     }
    #     print(context)
    return render(request, '3D_Scatter.html', locals())


# 保存文件
def save_scatterFile(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST":
        f = request.FILES['csv_file']
        print(type(f))
        file_path = os.path.join('media/upload', f.name)
        with open(file_path, 'wb') as fp:
            for info in f.chunks():
                fp.write(info)
            fp.close()
            message = '上传成功'
        data_set = read_csv(file_path, encoding='utf8')
        print(data_set.head())
        return render(request, 'scatter.html', locals())
    else:
        message = '上传失败'
    return render(request, 'scatter.html', locals())


# 散点图
def scatter(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    local_filename = "media/upload/"
    filename = os.listdir(local_filename)
    filename.sort(key=lambda fn: os.path.getatime(local_filename + fn) if not os.path.isdir(local_filename + fn) else 0)
    df = pd.read_csv('media/upload/{}'.format(filename[-1]), encoding='utf8')
    if request.method == "POST" and request.POST:
        scatter_title = request.POST.get('scatter_title', None)
        scatter_legend = request.POST.get('scatter_legend', None)
        dataset = request.POST.get('dataset', None)
        yy_values = dataset.split(",")
        yy_values = [int(yy_values[i]) for i in range(len(yy_values))]
        newdata = df.values.tolist()
        s_message = '图表创建成功'
        print(scatter_title, yy_values, scatter_legend, newdata)
    return render(request, 'scatter.html', locals())


# 保存文件
def save_wordCloudfile(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST":
        f = request.FILES['csv_file']
        print(type(f))
        file_path = os.path.join('media/upload', f.name)
        with open(file_path, 'wb') as fp:
            for info in f.chunks():
                fp.write(info)
            fp.close()
            message = '上传成功'
        return render(request, 'wordCloud.html', locals())
    else:
        message = '上传失败'
    return render(request, 'wordCloud.html', locals())


# 词云图
def wordCloud(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    if request.method == "POST" and request.POST:
        k_title = request.POST.get('k_title', None)
        sub_title = request.POST.get('sub_title', None)
        print(sub_title, k_title)
        local_filename = "media/upload/"
        filename = os.listdir(local_filename)
        filename.sort(
            key=lambda fn: os.path.getatime(local_filename + fn) if not os.path.isdir(local_filename + fn) else 0)
        with open('media/upload/{}'.format(filename[-1]), 'r', encoding='utf-8') as file:
            # 读取文件里面的全部内容
            comment_txt = file.read()
            # 使用jieba进行分割
            wordlist = jieba.cut(comment_txt)
            wl = "/".join(wordlist)
            # print(wl)
            # 设置词云形状图片
            import matplotlib
            matplotlib.use('Agg')
            mask = plt.imread("C:\PycharmProjects\dataAnalysis\static\img\map3.jpg")
            # 设置词云的一些配置，如：字体，背景色，词云形状，大小,生成词云对象
            wc = WordCloud(mask=mask, font_path="msyh.ttc", width=1000, height=700, background_color="white",
                           max_words=50,
                           scale=4, max_font_size=50, random_state=42)
            # 生成词云
            wc.generate(wl)
            # 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
            # 开始画图
            plt.imshow(wc, interpolation="bilinear")
            # 为云图去掉坐标轴
            plt.axis("off")
            plt.rcParams['font.sans-serif'] = ['SimHei']  # 这两行用来显示汉字
            plt.rcParams['axes.unicode_minus'] = False
            plt.title('词云图')
            sio = BytesIO()
            plt.savefig(sio, format='png', bbox_inches='tight', pad_inches=0.0)
            data = base64.encodebytes(sio.getvalue()).decode()
            src = 'data:image/png;base64,' + str(data)
            # # 记得关闭，不然画出来的图是重复的
            plt.close()
            w_message = '创建成功'
            return render(request, 'wordCloud.html', locals())
    return render(request, 'wordCloud.html', locals())
